/**
 * Created by chenyong on 2015/11/9.
 * 基于jQuery的BigPixel.Base基础插件
 */

var BrowserDetect={
    init:function()
    {
        this.browser=this.searchString(this.dataBrowser)||"An unknown browser";
        this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"an unknown version";
        this.OS=this.searchString(this.dataOS)||"an unknown OS";
        this.isMobile=this.isMobileDevice(this.MobileDevices)||false;
    },
    searchString:function(data){
        for(var i=0;i<data.length;i++)
        {
            var dataString=data[i].string;var dataProp=data[i].prop;
            this.versionSearchString=data[i].versionSearch||data[i].identity;
            if(dataString)
            {
                if(dataString.indexOf(data[i].subString)!=-1)return data[i].identity;
            }
            else if(dataProp)return data[i].identity;}
    },
    isMobileDevice:function(data){
        for(var i=0;i<data.length;i++)
        {
            var dataString=data[i].string;
            var dataProp=data[i].prop;
            this.versionSearchString=data[i].versionSearch||data[i].identity;
            if(dataString)
            {
                if(dataString.indexOf(data[i].subString)!=-1)return true;
            }
            else if(dataProp)return false;
        }
    },
    searchVersion:function(dataString){var index=dataString.indexOf(this.versionSearchString);if(index==-1)return;return parseFloat(dataString.substring(index+this.versionSearchString.length+1));},
    dataBrowser:[
        {string:navigator.userAgent,subString:"Chrome",identity:"Chrome"},
        {string:navigator.userAgent,subString:"OmniWeb",versionSearch:"OmniWeb/",identity:"OmniWeb"},
        {string:navigator.vendor,subString:"Apple",identity:"Safari",versionSearch:"Version"},
        {prop:window.opera,identity:"Opera",versionSearch:"Version"},
        {string:navigator.vendor,subString:"iCab",identity:"iCab"},
        {string:navigator.vendor,subString:"KDE",identity:"Konqueror"},
        {string:navigator.userAgent,subString:"Firefox",identity:"Firefox"},
        {string:navigator.vendor,subString:"Camino",identity:"Camino"},
        {string:navigator.userAgent,subString:"Netscape",identity:"Netscape"},
        {string:navigator.userAgent,subString:"MSIE",identity:"Explorer",versionSearch:"MSIE"},
        {string:navigator.userAgent,subString:"Trident",identity:"Explorer",versionSearch:"rv"},
        {string:navigator.userAgent,subString:"Gecko",identity:"Mozilla",versionSearch:"rv"},
        {string:navigator.userAgent,subString:"Mozilla",identity:"Netscape",versionSearch:"Mozilla"}
    ],
    MobileDevices:[
        {string:navigator.userAgent,subString:"iPhone",identity:"iPhone"},
        {string:navigator.userAgent,subString:"Android",identity:"Android"}

    ],
    dataOS:[
        {string:navigator.platform,subString:"Win",identity:"Windows"},
        {string:navigator.platform,subString:"Mac",identity:"Mac"},
        {string:navigator.userAgent,subString:"iPhone",identity:"iPhone/iPod"},
        {string:navigator.platform,subString:"Linux",identity:"Linux"}
    ]
};
BrowserDetect.init();

jQuery.support.cors = true;
(function ($) {

    //缓存工厂
    $.createCache = function( requestFunction ) {
        var cache = {};
        return function( key, callback ) {
            if ( !cache[ key ] ) {
                cache[ key ] = $.Deferred(function( defer ) {
                    requestFunction( defer, key );
                }).promise();
            }
            return cache[ key ].done( callback );
        };
    };

    //加载js文件
    $.cachedGetScript = $.createCache(function(defer,url){
        //$.getScript( url ).then( defer.resolve, defer.reject );
        $.ajax({
            url:url,
            dataType:"script",
            cache:true,
            success:defer.resolve,
            error:defer.reject
        });
    });

    //获取Url参数
    $.getUrlParam = function (name){
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    };

    //增加或更新Url参数值
    $.updateUrlParams = function(url, name, value){
        var r = url;
        if (r != null && r != 'undefined' && r != "") {
            value = encodeURIComponent(value);
            var reg = new RegExp("(^|)" + name + "=([^&]*)(|$)");
            var tmp = name + "=" + value;
            if (url.match(reg) != null) {
                r = url.replace(eval(reg), tmp);
            }
            else {
                if (url.match("[\?]")) {
                    r = url + "&" + tmp;
                } else {
                    r = url + "?" + tmp;
                }
            }
        }
        return r;
    };

    //设置Cookie
    $.setCookie = function(name,value,expire)
    {
        var exp = new Date();
        exp.setTime(exp.getTime() + expire*60*1000);
        var _domain = window.location.hostname;
        document.cookie = name + "="+ decodeURI (value) + ";expires=" + exp.toGMTString() + ";domain="+_domain + ";path=/";
    }
    //读取Cookie
    $.getCookie = function(name)
    {
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg))
            return decodeURI(arr[2]);
        else
            return null;
    }

    //删除Cookie
    $.removeCookie = function(name)
    {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval=getCookie(name);
        if(cval!=null)
            document.cookie= name + "="+cval+";expires="+exp.toGMTString();
    }



    var settings = {
        'debug': false,
        'timeout': 120
    };

    $.currentUser = {};

    var _getCurrentUserInfo = function(callback){
        $.ajax({
            type: "GET",
            url: "/auth/me",
            beforeSend: function(request) {
                request.setRequestHeader("authorization", "Bearer " + $.getCookie("token"));
            },
            success: function(userinfo){
                callback(null,userinfo);
            },
            error: function(err)
            {
                callback(err);
            }
        });
    }

    //当前用户

    if ($.getCookie("token")) {
        _getCurrentUserInfo(function(err,data){
            if(!err)
            {
                $.currentUser = data;
                var args  = Array.prototype.slice.call(arguments);
                if(typeof(  $.bigpixel.OnUserinfoReadyFunc) == "function" ){
                    $.bigpixel.OnUserinfoReadyFunc.apply(null,args);
                }
            }
        });
    }

    var methods = {
        debug: function () {
            return settings.debug;
        },

        AjaxGetJson:function(url,data,callback)
        {
            if (arguments.length === 2 && typeof data === 'function') {
                callback = data;
                data = null;
            }

            $.ajax({
                type: "GET",
                timeout:3000,
                url: url,

                beforeSend: function(request) {
                    if($.getCookie("token"))
                    {
                        request.setRequestHeader("authorization", "Bearer " + $.getCookie("token"));
                    }
                },
                success: function(d){
                    callback(null,d);
                },
                error: function(e)
                {
                    callback(e);
                }
            });

        },
        AjaxPostData:function(url,data,callback)
        {
            if (arguments.length === 2 && typeof data === 'function') {
                callback = data;
                data = null;
            }
            $.ajax({
                type: "POST",
                timeout:3000,
                url: url,
                data:data,
                beforeSend: function(request) {
                    if($.getCookie("token"))
                    {
                        request.setRequestHeader("authorization", "Bearer " + $.getCookie("token"));
                    }
                },
                success: function(d){
                    callback(null,d);
                },
                error: function(e)
                {
                    callback(e);
                }
            });
        },

        AjaxPutData:function(url,data,callback)
        {
            if (arguments.length === 2 && typeof data === 'function') {
                callback = data;
                data = null;
            }
            $.ajax({
                type: "PUT",
                timeout:3000,
                url: url,
                data:data,
                beforeSend: function(request) {
                    if($.getCookie("token"))
                    {
                        request.setRequestHeader("authorization", "Bearer " + $.getCookie("token"));
                    }
                },
                success: function(d){
                    callback(null,d);
                },
                error: function(e)
                {
                    callback(e);
                }
            });
        },

        //判断Url是否有效
        IsValidUrl:function(url,callback)
        {
            $.ajax({
                url: url,
                type: 'HEAD',
                timeout:1500,
                complete: function(response) {
                    $.ajaxSetup({timeout:3000});
                    if(response.status == 200) {
                        callback(true);
                    } else {
                        callback(false);
                    }
                }
            });
        },
        getCurrentUser:function(callback)
        {
            if($.currentUser.hasOwnProperty('_id'))
            {
                callback(currentUser);
            }
            else if (!$.getCookie("token"))
            {
                callback(null);
            }
            else
            {
                this.AjaxGetJson("/auth/me",function(err,data){
                  if(!err)
                  {
                      $.currentUser = data;
                      var args  = Array.prototype.slice.call(arguments);
                      if(typeof(  $.bigpixel.OnUserinfoReadyFunc) == "function" ){
                          $.bigpixel.OnUserinfoReadyFunc.apply(null,args);
                      }
                      callback($.currentUser);
                  }
                    else
                  {
                      callback(null);
                  }
                });
            }
        },
        //登录
        login:function(){
            var _currUrl = window.location.href;
            var krpano = document.getElementById("panoSWFObject");
            if(krpano != null)
            {
                var fov = Number( krpano.get("view.fov") );
                var v = Number( krpano.get("view.vlookat") );
                var h   = Number( krpano.get("view.hlookat") );
                h = h%360; // restrict to +-360
                if (h<=-180){
                    h = 360+h;
                }
                else if(h>180){
                    h = 360-h;
                }
                //pos = {'fov':fov,'ath':h,'atv':v};

                _currUrl = $.updateUrlParams(_currUrl,'ath',h);
                _currUrl = $.updateUrlParams(_currUrl,'atv',v);
                _currUrl = $.updateUrlParams(_currUrl,'fov',fov);
            }
            $.setCookie("reutrnurl",_currUrl,30);

            //微信登陆

            window.location.href = '/auth/wechat?returnurl=' + _currUrl;

        },
        //注销
        logout:function(){
            $.removeCookie("token");
            $.currentUser = {};
        },
        isLoggedIn: function() {
            return $.currentUser.hasOwnProperty('_id');
        },
        //检测是否登录
        isLoggedInAsync:function(callback){
            if($.currentUser.hasOwnProperty('_id'))
            {
                callback($.currentUser.hasOwnProperty('_id'));
            }
            else if (!$.getCookie("token"))
            {
                callback(false);
            }
            else
            {
                this.AjaxGetJson("/auth/me",function(err,data){
                    if(!err)
                    {
                        $.currentUser = data;
                        var args  = Array.prototype.slice.call(arguments);
                        if(typeof(  $.bigpixel.OnUserinfoReadyFunc) == "function" ){
                            $.bigpixel.OnUserinfoReadyFunc.apply(null,args);
                        }
                    }
                    callback($.currentUser.hasOwnProperty('_id'));
                });
            }
        },
        OnUserinfoReady:function(func)
        {
            $.bigpixel.OnUserinfoReadyFunc = func;
        },
        //初始化微信分享
        initWechat:function(){
            var ua = navigator.userAgent.toLowerCase();
            if(ua.match(/MicroMessenger/i)=="micromessenger") {
                $.cachedGetScript('http://res.wx.qq.com/open/js/jweixin-1.0.0.js',function(){
                    if(typeof(socialinfo) == "object")
                    {
                        $.getJSON('http://srv.bigpixel.cn/api/weixin/getsignature?url=' + encodeURIComponent(socialinfo.link)).done(function (data) {

                            wx.config({debug: false, appId: data.appId, timestamp: data.timestamp, nonceStr: data.nonceStr, signature: data.signature, jsApiList: ['onMenuShareTimeline', 'onMenuShareQQ', 'onMenuShareAppMessage', 'onMenuShareWeibo']});
                            wx.ready(function () {
                                wx.onMenuShareTimeline(socialinfo);
                                wx.onMenuShareAppMessage(socialinfo);
                                wx.onMenuShareQQ(socialinfo);
                                wx.onMenuShareWeibo(socialinfo);
                            });
                        });
                    }
                });
            }
        },
        //重置微信分享链接
        resetWechatShareInfo:function(shareinfo)
        {
            wx.ready(function () {
                wx.onMenuShareTimeline(shareinfo);
                wx.onMenuShareAppMessage(shareinfo);
                wx.onMenuShareQQ(shareinfo);
                wx.onMenuShareWeibo(shareinfo);
            });

        }
    };

    $.bigpixel = methods;

}(jQuery));


/**
 * Created by chenyong on 2015/11/14.
 */

/*
用户标注点
 */
var UserTags = function(panoId){
    this.panoId = "";
    if (arguments.length === 1)
    {
        this.panoId = panoId;
    }

    this.arrTags = [];
    this.tagsvisible = true;

    self = this;

    //当接收到随机的标注点时触发
    var _onReceivedRandomTagsEvent;
    var limit = 100;
    var skip = 0;
    var sure_trigger=false;

    this.tagworker = new Worker("/scripts/worker/usertag-worker.js");
    this.tagworker.onerror = function(event){
        console.log(event);
    }
    this.tagworker.onmessage = function(event){
        //返回标注点列表
        if(event.data.msgtype && event.data.msgtype == "getusertags")
        {
            var data = event.data.list;
            //移除现有标注点
            for(var i=0;i<self.arrTags.length;i++)
            {
                var _taginfo = self.arrTags[i];
                //bpsviewer.call('removehotspot('+_taginfo.id+');');
                //bpsviewer.call('removeplugin('+_taginfo.id+'_url'+');');
                //bpsviewer.call('removeplugin('+ _taginfo.id+'_name'+');');
            }
            self.arrTags = [];
            //添加标注点
            for(var i=0;i<data.length;i++){
                self.arrTags.push(data[i]);
                self.createTag(data[i]);
            }
            if(event.data.total > (event.data.skip + limit))
            {
                skip = skip + limit;
            }
            else
            {
                skip = 0;
            }
        }
        if(event.data.msgtype && event.data.msgtype == "getusertags-error")
        {
            setTimeout("self.getUserTagsDataWorker();",2000);
        }
        //getusertags-error

        //返回随机标注点
        if(event.data.msgtype && event.data.msgtype == "randomusertags")
        {
            var data = event.data.list;
            if(typeof(_onReceivedRandomTagsEvent) == "function" )
            {
                _onReceivedRandomTagsEvent.call(null,data);
            }
        }

    }

    var setTagVisible = function(taginfo,visibility)
    {
        taginfo.visible=visibility;
        bpsviewer.set('hotspot['+taginfo.id+'].visible',visibility);
    }

    this.OnReceivedRandomTags = function(func)
    {
        _onReceivedRandomTagsEvent = func;
    }
    this.refreshTags = function(){
        var fov = bpsviewer.get("view.fov");
        $.each(self.arrTags,function(i,taginfo){
            var visible = self.tagsvisible;
            var zoomlevel = taginfo.fov / fov;
            if(zoomlevel >1.8 || zoomlevel < 0.5)
            {
                visible = false;
            }

            if(visible){
                if(!taginfo.visible){
                    setTagVisible(taginfo,true);
                }
            }
            else{
                setTagVisible(taginfo,false);
            }
        });
    }

//转换TagInfo格式
    function convertTaginfo(data)
    {
        var _taginfo = {};
        _taginfo.id = "usertag" + data._id;
        _taginfo.ath = data.ath;
        _taginfo.atv = data.atv;
        _taginfo.fov = data.fov;
        if(typeof(data.userinfo) == "object" )
        {
            _taginfo.avatarurl =  data.userinfo.headimgurl;
        }
        else
        {
            _taginfo.avatarurl = "/images/noavatar@96x96.jpg";
        }

        _taginfo.title = data.title;
        _taginfo.note = data.note;

      if(data.attached != undefined && typeof(data.attached) == "string")
      {
        _taginfo.attached = JSON.parse(data.attached);
      }
      else if (data.attached != undefined && typeof(data.attached == "object") )
      {
        _taginfo.attached = data.attached;
      }
        return _taginfo;
    }

    //从后台读取数据添加用户标注点到视图中
    this.createTag = function(taginfo)
    {
        //console.log(taginfo);
        var tagid = taginfo.id;
        var tag_url = "http://cdn.bigpixel.cn/gpx/ngrunning/usertag_bg01.png";
        if(typeof(taginfo.attached) == 'object' )
        {
            tag_url = "http://cdn.bigpixel.cn/gpx/ngrunning/usertag_bg02.png";
        }
        bpsviewer.call('addhotspot('+tagid+');');
        bpsviewer.set('hotspot['+tagid+'].url',tag_url);
        bpsviewer.set('hotspot['+tagid+'].visible',true);
        bpsviewer.set('hotspot['+tagid+'].ath',taginfo.ath);
        bpsviewer.set('hotspot['+tagid+'].atv',taginfo.atv);
        bpsviewer.set('hotspot['+tagid+'].edge',"bottom");
        bpsviewer.set('hotspot['+tagid+'].zoom',true);
        bpsviewer.set('hotspot['+tagid+'].scale',0.02);

        bpsviewer.set('hotspot['+tagid+'].title',taginfo.title);
        bpsviewer.set('hotspot['+tagid+'].note',taginfo.note);
        bpsviewer.set('hotspot['+tagid+'].avatarurl',taginfo.avatarurl);



        if(taginfo.attached != undefined && typeof(taginfo.attached == "object") && taginfo.attached.code != undefined )
        {

            bpsviewer.set('hotspot['+tagid+'].code',taginfo.attached.code);      //跑者的编号
            bpsviewer.set('hotspot['+tagid+'].crop1','1|627|318|112');      //跑者点击背景
            bpsviewer.set('hotspot['+tagid+'].css1','text-align:left; padding-left:62px;padding-top:15px; color:#ffffff; font-family:Arial; font-size:18px;'); //跑者说的话
        }else{
            bpsviewer.set('hotspot['+tagid+'].code','');      //跑者的编号
            bpsviewer.set('hotspot['+tagid+'].crop1','0|513|318|112');      //跑者点击背景
            bpsviewer.set('hotspot['+tagid+'].css1','text-align:left; padding-left:62px;padding-top:15px; color:#000000; font-family:Arial; font-size:18px;'); //跑者说的话
        }
        bpsviewer.set('hotspot['+tagid+'].onclick','showtaginfo(\''+tagid + '\')');
        if(sure_trigger){
            bpsviewer.call('showtaginfo(\''+tagid + '\')');
            sure_trigger=false;
        }
    }
    //创建用户标注点成功后执行，在这里绑定当前id到链接上
    this.CreateUsertagSuccess = function(taginfo)
    {
        sure_trigger=true;
        this.createTag(convertTaginfo(taginfo));
        self.arrTags.push(taginfo);
        bpsviewer.call("set(hotspot[tagger].visible,false);");
        $(".wx_y").slideUp(100);
        bpsviewer.call('set(plugin[tag_home_btn].visible,true);');
    }

    /**
     * 保存新增加的用户标注点
     */
    this.saveNewtag = function(note,attached)
    {
        if($.bigpixel.isLoggedIn()){
            var data = {
                userid:$.currentUser._id,
                ath:bpsviewer.get('hotspot[tagger].ath'),
                atv:bpsviewer.get('hotspot[tagger].atv'),
                fov:bpsviewer.get('hotspot[tagger].fov') || 10,
                note:note,
              attached:JSON.stringify(attached)

            };

            //如果当前用户已经有标注点，则修改标注点信息，否则创建新的标注点
            this.getTaginfoByUserId(data.userid,function(taginfo){
                if(taginfo != null)
                {
                    //修改标注点
                    var tagid =  taginfo.id.replace("usertag", "");
                    var _url = "/service/panos/" + self.panoId + "/usertags/"+tagid;
                    $.bigpixel.AjaxPutData(_url,data,function(err,data){
                        if(!err)
                        {
                            self.CreateUsertagSuccess(data);
                        }
                    });
                }
                else
                {
                    //新增标注点
                    var _url = "/service/panos/" + self.panoId + "/usertags";
                    $.bigpixel.AjaxPostData(_url,data,function(err,data){
                        if(!err)
                        {
                            self.CreateUsertagSuccess(data);
                        }
                    });
                }
            })
        }
        else
        {
            console.log("请登录");
        }
    }

    //
    this.getUserTagsDataWorker = function(){
        var eventdata = {
            msgtype:"getusertags",
            panoid:self.panoId,
            limit:limit,
            skip:skip,
            gendar:""
        };
        self.tagworker.postMessage(eventdata);
    }
    //从这里 可以成功返回随机标注点得到返回data数据
    this.getRandomTagsDataWorker = function(){

      var count = 4;
      var devicewidth = document.documentElement.clientWidth;
      if (devicewidth >= 360 && devicewidth < 450)
      {
        count = 6;
      }
      else if (devicewidth >= 450)
      {
        count = 8;
      }

        var eventdata = {
            msgtype:"randomusertags",
            panoid:self.panoId,
            count:count
        };
        self.tagworker.postMessage(eventdata);

    }

    //隐藏所有标签
    this.hide_alltags=function(){
      for(var i=0;i<self.arrTags.length;i++){
        setTagVisible(self.arrTags[i],false);
      }
    }

    //显示所有标签
    this.show_alltags=function(){
      for(var i=0;i<self.arrTags.length;i++){
        setTagVisible(self.arrTags[i],true);
      }
    }

    this.isExistsTag = function(taginfo){
        console.log(self.arrTags.length);
        for(var i=0;i<self.arrTags.length;i++){
            if(taginfo.id==self.arrTags[i].id){
                return true;
            }
        }
        return false;
    }

    //旋转到标注点
    this.looktoTag=function(taginfo)
    {
        var arrTags_flag=false;
        $(".fans_list_box").css("display","none");
        bpsviewer.call("set(plugin[cover_hei].visible,false);");

        if(!self.isExistsTag(taginfo)){
            console.log("not exists Push ---------begin");
            console.log(taginfo);
            self.arrTags.push(taginfo);  //push到数组里
            self.createTag(taginfo);   //生成一个新的tag标签

            console.log("not exists Push ---------end");
        }
        bpsviewer.call("showtaginfo(" + taginfo.id + ");");
        bpsviewer.call("zoomto(60,linear(50));moveto("+taginfo.ath+","+taginfo.atv+",linear(60));Wait(0.5);zoomto(1,linear(50));");

    }
    //根据user_id得到相应的信息
    this.getTaginfoByUserId = function(uid,cb)
    {
        var _url = "/service/panos/" + self.panoId + "/usertags?userid="+uid;
        $.bigpixel.AjaxGetJson(_url,function(err,body){
            var data = body.data;

            if(!err && data.length > 0)
            {
                var _taginfo = convertTaginfo(data[0]);
                cb(_taginfo);
            }
            else
            {
                cb(null);
            }
        });
    }

    /**
     * 初始化
     * @constructor
     */
    this.Init = function(panoId)
    {
        self.panoId = panoId;
        //self.getUserTagsDataWorker();
        self.getRandomTagsDataWorker();

    }

    // //显示标注自己想说的话的input框-start
    this.showdialog=function(){
        if( $.bigpixel.isLoggedIn())
        {
            $(".wx_y").slideDown(100);
            var atv = Number( bpsviewer.get("view.vlookat") );
            var ath   = Number( bpsviewer.get("view.hlookat") );
            bpsviewer.call("set(hotspot[tagger].visible,true);");
            bpsviewer.call("set(hotspot[tagger].ath,"+ath+");");
            bpsviewer.call("set(hotspot[tagger].atv,"+atv+");");
            bpsviewer.call("set(plugin[user_name].html,"+ $.currentUser.nickname+");");
            bpsviewer.call("set(plugin[usericon_avatar].url,"+ $.currentUser.avatarurl+");");
        }
        else
        {
            $(".wx_n").slideDown(100);
        }
        bpsviewer.call("set(plugin[tag_home_btn].visible,false);");
    }

    //生成女粉丝列表
    this.create_female_list=function(){
        var woman_fans_html='';
        var limit_num=6;
        var Tag_index=woman_page*limit_num;
        //var _url = "/service/panos/nacc20151114/fans?skip="+woman_page+"&limit=6&sex=2";
        var _url = "/service/panos/" + self.panoId + "/usertags?skip="+Tag_index+"&limit="+limit_num+"&gendar=2";
        $.bigpixel.AjaxGetJson(_url,function(err,data){
            if(!err)
            {
                var TagsDate=data.data;
                var len=TagsDate.length;
                if(len!=0){
                    for(var i=0;i<len;i++)
                    {
                        var _taginfo = convertTaginfo(TagsDate[i]);


                        var strtaginfo = JSON.stringify(_taginfo);
                        var usename=TagsDate[i].userinfo.nickname;
                        woman_fans_html+=  '<li><div class="fans_head_img fl"><img src="'+TagsDate[i].userinfo.headimgurl.replace("/0","/96")+'"/></div>\
					<div class="fans_text fl"><p class="nickname">'+usename+'</p><p class="text">'+TagsDate[i].note+'</p></div>\
					<div class="fans_tag_area fr"><a class="zoom_self fl" href="javascript:void(0);" onclick=\'bpsviewer.UserTags.looktoTag(' + strtaginfo + ')\'>\
					<span class="icon-crosshairs"></span></a></div></li>';
                    }
                    $("#fans_list_woman").append(woman_fans_html  );
                    var list_woman_h=parseInt($("#fans_list_woman").height());
                    if(list_woman_h>300){
                        $(".pullUp_woman").css("display","table");
                        pullUp_woman_flag=true;
                        $(".pullUp_woman .pullUpLabel").html('加载更多...');
                    }else{ $(".pullUp_woman").css("display","none"); }
                }else{
                    if(woman_page==0){
                        $(".pullUp_woman").css("display","table");
                        pullUp_woman_flag=true;
                        $(".pullUp_woman .pullUpLabel").html('还没有更多女粉丝，来抢沙发吧');
                    }else{
                        $(".pullUp_woman").css("display","none");
                    }
                }
                $(".pullUp_woman").removeClass('loading');
            }
        });
        woman_flag=false;
    }
    //生成男粉丝列表
    this.create_male_list=function(){
        var man_fans_html='';
        //var _url = "/service/panos/" + self.panoId + "/fans?skip="+man_page+"&limit=6&sex=1";
        var limit_num=6;
        var Tag_index=man_page*limit_num;
        var _url = "/service/panos/" + self.panoId + "/usertags?skip="+Tag_index+"&limit="+limit_num+"&gendar=1";
        $.bigpixel.AjaxGetJson(_url,function(err,data){
            if(!err)
            {
                var TagsDate=data.data;
                var len=TagsDate.length;
                if(len!=0){
                   // console.log(JSON.stringify(data));
                    for(var i=0;i<len;i++)
                    {
                        var _taginfo = convertTaginfo(TagsDate[i]);
                        var strtaginfo = JSON.stringify(_taginfo);
                        var usename=TagsDate[i].userinfo.nickname;
                        //console.log(i+'='+usename);
                        man_fans_html+=  '<li><div class="fans_head_img fl"><img src="'+TagsDate[i].userinfo.headimgurl+'"/></div>\
					<div class="fans_text fl"><p class="nickname">'+usename+'</p><p class="text">'+TagsDate[i].note+'</p></div>\
					<div class="fans_tag_area fr"><a class="zoom_self fl" href="javascript:void(0);" onclick=\'bpsviewer.UserTags.looktoTag(' + strtaginfo + ')\'>\
					<span class="icon-crosshairs"></span></a></div></li>';
                    }

                    $("#fans_list_man").append(man_fans_html  );
                    var list_woman_h=parseInt($("#fans_list_man").height());
                    if(list_woman_h>300){
                        $(".pullUp_man").css("display","table");
                        pullUp_man_flag=true;
                        $(".pullUp_man .pullUpLabel").html('加载更多...');
                    }else{ $(".pullUp_man").css("display","none"); }
                }else{
                    if(man_page==0){
                        $(".pullUp_man").css("display","table");
                        pullUp_man_flag=true;
                        $(".pullUp_man .pullUpLabel").html('还没有更多男粉丝，来抢沙发吧');
                    }else{
                        $(".pullUp_man").css("display","none");
                    }
                }
                $(".pullUp_man").removeClass('loading');
            }
        });
        man_flag=false;
    }

    //zoom到一个地方去
    this.zoom_go=function(x1,y1,fov){
        $(".fans_list_box").css("display","none");
        bpsviewer.call("set(plugin[cover_hei].visible,false);");
        //bpsviewer.call("zoomto(70,linear(50));moveto("+x1+","+y1+",linear(60));Wait(0.5);zoomto("+fov+",linear(50));");
        bpsviewer.call("moveto("+x1+","+y1+",linear(60));Wait(0.5);zoomto("+fov+",linear(50));");
    }

}

/**
 * Created by chenyong on 15/11/26.
 * 让IE 10以下的浏览器兼容Web Worker功能
 */

var self;

/**
 * 当浏览器不支持Web Worker时
 * 构造一个BpsWorker对象
 */
if(typeof Worker === 'undefined') {
    Worker = function(worker)
    {
        return new BpsWorker(worker);
    };
}


/**
 * 加载脚本
 * @param src
 */
function importScripts(src)
{
    $.ajax({
        url : src,
        dataType : 'script',
        async : false
    });
}


/**
 * BpsWorker主函数
 * @param worker
 * @constructor
 */
function BpsWorker(worker)
{
    var script = document.createElement('script'),
        func = this,
        num_workers;

    this.ready = true;

    this.queue = [];

    if(typeof BPSWORKER === 'undefined') {
        BPSWORKER = {};
        BPSWORKER.self = self;
        BPSWORKER.workers = [];
    }

    num_workers = BPSWORKER.workers.length;
    BPSWORKER.workers[num_workers] = {};
    this.worker_id = num_workers;
    this.worker_url = worker;


    if(typeof $ !== 'object') {
        this.loadJQuery(function() {
            func.loadWorker();
        });
    }

    func.loadWorker();

    this.onmessage = {};

    BPSWORKER.workers[this.worker_id].postMessage = function(message) { func.returnMessage(message); };
    self = BPSWORKER.workers[this.worker_id];

}


BpsWorker.prototype = {
    /**
     * 使用postmessage函数向worker发送请求
     * @param message
     */
    postMessage : function(message) {
        if(!this.ready) {
            this.queue.push(message);
            return;
        }
        self = BPSWORKER.workers[this.worker_id];
        BPSWORKER.workers[this.worker_id].onmessage({'data' : message});
        self = BPSWORKER.self;
    },


    /**
     * 返回消息
     * @param message
     */
    returnMessage : function(message) {
        this.onmessage({'data' : message});
    },

    /**
     * 加载JQuery
     * @param callback
     */
    loadJQuery : function(callback) {
        this.ready = false;
        var jquery_lib = document.createElement('script');
        jquery_lib.type = 'text/javascript';
        jquery_lib.src = 'http://cdn.bigpixel.cn/libs/jquery/jquery-1.11.3.min.js';
        document.body.appendChild(jquery_lib);
        jquery_lib.onreadystatechange = callback;
        jquery_lib.onload = callback;
    },


    /**
     * 使用Ajax加载工作队列
     * 处理工作队列
     */
    loadWorker : function() {
        this.ready = true;

        var func = this;

        self = BPSWORKER.workers[this.worker_id];
        $.ajax({
            url : func.worker_url,
            dataType : 'script',
            async : false
        });
        self = BPSWORKER.self;

        this.processQueue();
    },

    /**
     * 处理工作队列中的Worker js
     */
    processQueue : function() {
        var queue = this.queue,
            len = queue.length,
            i;

        for(i=0;i<len;i++) {
            this.postMessage(queue[i]);
        }
        this.queue = [];
    }
};
/**
 * Created by chenyong on 15/11/16.
 * 超级像素全景对象
 * 所有的全景图皆由此对象创建，并生成一个document.bpsviewer的全景变量
 *
 *  bpsviewer=new BigPixelViewer("<%= tourxmlpath%>","swift1989");
 *  document.bpsviewer=bpsviewer;
 *  bpsviewer.embed();;
 */

var BigPixelViewer=function(xml,panoId){

    var lastFov;
    var lastHlookat;
    var lastVlookat;

    //当视图发生改变时触发的事件
    var _onviewerChangEvent;

    var self=this;
    this.krpano=null;
    this.isReady=false;
    this.panoId = panoId;

    this.krpanoReady=function(krpano){

        //console.log(BrowserDetect.isMobile);
        if(BrowserDetect.isMobile)
        {
            var _stagescale =document.documentElement.clientWidth /320 /2;
            krpano.set("stagescale", _stagescale);
        }

        if(self!=null&&krpano!=null)
            self.krpano=krpano;
        if(self==null||self.krpano==null)
            return;
        self.waitPano(function()
        {
            self.isReady=true;
            BpsViewerReady();
        });
    };

    this.waitPano=function(callback){
        var isReady=false;
        self.call("addhotspot(ngrunning)");
        try{
            var test=self.get("hotspot[ngrunning]");
            if(test!=null&&test.sprite!=null)
            {
                isReady=true;
            }
        }
        catch(e)
        {isReady=false;}
        if(isReady){if(!self.isReady){self.call("removehotspot(ngrunning)");callback();}}else setTimeout(function(){self.waitPano(callback);},10);
    };

    var html5="prefer";

    if(BrowserDetect.browser=="Explorer"&&BrowserDetect.version<=10)
        html5="never";
    else if(BrowserDetect.browser=="Explorer")
        html5="prefer+css3d";
    this.viewer=createPanoViewer({swf:"http://cdn.bigpixel.cn/libs/krpano/1.18.5/tour.swf",js:"http://cdn.bigpixel.cn/libs/krpano/1.18.5/tour.js",xml:xml,target:"pano-container",html5:html5,passQueryParameters:false,onready:this.krpanoReady,wmode:"opaque"});

    this.call=function(action){this.krpano.call(action);};
    this.set=function(variable,value){this.krpano.set(variable,value);};
    this.get=function(variable){return this.krpano.get(variable);};
    this.embed=function(){this.viewer.embed();};
    this.zoomInDown=function(){this.set('fov_moveforce',-0.75);};
    this.zoomOutDown=function(){this.set('fov_moveforce',+0.75);};
    this.zoomUp=function(){this.set('fov_moveforce',0);};
    this.moveLeftDown=function(){this.set('hlookat_moveforce',-0.75);};
    this.moveRightDown=function(){this.set('hlookat_moveforce',+0.75);};
    this.moveTopDown=function(){this.set('vlookat_moveforce',-0.75);};
    this.moveBottomDown=function(){this.set('vlookat_moveforce',+0.75);};
    this.moveUp=function(){this.set('vlookat_moveforce',0);this.set('hlookat_moveforce',0);};

    function BpsViewerReady(){
        lastFov=self.krpano.get('view.fov');
        lastHlookat=self.krpano.get('view.hlookat');
        lastVlookat=self.krpano.get('view.vlookat');
        self.krpano.set('events.onviewchanged','js(bpsviewer.BpsViewerChanged(););');
    }

    this.BpsViewerChanged = function(){
        var fov=self.krpano.get('view.fov');
        var hlookat=self.krpano.get('view.hlookat');
        var vlookat=self.krpano.get('view.vlookat');

        if(Math.abs(lastFov-fov)>fov/50||Math.abs(lastHlookat-hlookat)>1||Math.abs(lastVlookat-vlookat)>1)
        {
            lastFov=fov;
            lastHlookat=hlookat;
            lastVlookat=vlookat;
            var args  = Array.prototype.slice.call(arguments);
            if(typeof(_onviewerChangEvent) == "function" )
            {
                _onviewerChangEvent.apply(null,args);
            }
        }
    }

    this.OnBpsViewerChanged = function(func)
    {
        _onviewerChangEvent = func;
    }

    //加载
    if(typeof UserTags=='function')
    {
        console.log(typeof UserTags);
        this.UserTags = new UserTags(this.panoId);
    }

}